#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.web.helper;

import ${package}.web.security.AuthUser;
import guda.grape.mvc.session.util.ServerCookie;
import org.springframework.beans.factory.InitializingBean;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by well on 16/8/24.
 */
public class CookieLogFilter implements Filter,InitializingBean {


    private String cookieDomain;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        if(servletResponse instanceof  HttpServletResponse ){
            HttpServletResponse response = (HttpServletResponse)servletResponse;
            //HttpServletRequest request = (HttpServletRequest)servletRequest;
            if(AuthUser.getCurrentUser()!=null && AuthUser.getCurrentUser().getUserId()!=null){
                Cookie cookie = new Cookie("u_t",String.valueOf(AuthUser.getCurrentUser().getUserId()));
                if(cookieDomain==null) {
                    cookie.setDomain("");
                }else{
                    cookie.setDomain(cookieDomain);
                }
                cookie.setMaxAge(-1);
                cookie.setHttpOnly(true);
                cookie.setPath("/");
                cookie.setSecure(true);

                StringBuilder buf = new StringBuilder();
                ServerCookie.appendCookieValue(buf,
                        cookie.getVersion(),
                        cookie.getName(),
                        "",
                        cookie.getPath(),
                        cookie.getDomain(),
                        cookie.getComment(),
                        0,
                        cookie.getSecure(),
                        true);
                response.addHeader("Set-Cookie", buf.toString());
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    public void setCookieDomain(String cookieDomain) {
        this.cookieDomain = cookieDomain;
    }
}
